package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgInvoiceOffset;
import com.ys.entity.sys.YsCol;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgInvoiceOffsetService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 发票管理
 */
@Controller
@RequestMapping("/api/inter/tcgInvoiceOffsetByManage")
public class ApiInterTcgInvoiceOffsetByManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgInvoiceOffsetByManageController.class);

    @Autowired
    private CommonApiService<TcgInvoiceOffset> commonApiService;

    @Autowired
    private TcgInvoiceOffsetService tcgInvoiceOffsetService;

    //菜单id
    private Long menuId = MenuId.TCG_InvoiceOffset_ByManage;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgInvoiceOffsetByManage:view";
    private final String PERMISSIONS_ADD = "tcgInvoiceOffsetByManage:cancelInfo";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgInvoiceOffset setSeachSql(TcgInvoiceOffset cond){

        cond

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyVid ")//公司信息表
                .addField("C.Vname AS vname")//购买方公司名称
                .addField("C.Tax AS tax")//购买方公司税号

                .addLeftJoin("TCW_PartnerBankInfo PBI ON PBI.Id = A.PartnerBankInfoId ")//合作商银行账户管理
                .addField("PBI.PartnerName AS partnerName")//供应方公司名称
                .addField("PBI.Vgssh AS vgssh")//供应方公司税号

                .addLeftJoin("TCG_InvoiceOffsetItem S ON S.Pbid = A.Bid ")//子表
                .addField("S.InvoiceModelNo AS invoiceModelNo")//发票型号
                .addField("S.InvoiceName AS invoiceName")//发票品名
                .addField("S.OffsetNum AS offsetNum")//发票本次核销数量、子件数量
                .addField("S.OffsetAmount AS offsetAmount")//本次核销金额、子件总额（含税）
                .addField("S.CustomsNum AS customsNum")//子件报关数量

                .addLeftJoin("TCG_PurchaseContractItem PCI ON PCI.Id = S.PurchaseContractItemId ")//采购合同管理子表
                .addField("PCI.Pbid AS purchaseContractBid")//采购合同单号
                .addField("PCI.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("PCI.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                //.addField("PCI.SubPurchasePrice AS subPurchasePrice")//子件采购单价、子件单价（含税）
                .addField("PCI.SubWriteOffNum AS subWriteOffNum")//子件已核销数量

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent PAC ON PAC.Id = PCI.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PAOI ON PAOI.Id = PAC.Pid")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PAOI.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addField("PPC.Bid AS appointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PAOI.ProductCode AS productCode")//商品编码
                .addField("PAOI.ProductName AS productName")//商品名称
                .addField("PAOI.CodeMerge AS codeMerge")//合并商品编码
                .addField("PAC.SubCode AS subCode")//子件编码
                .addField("PAC.SubName AS subName")//子件名称
                .addField("PAC.SubCodeMerge AS subCodeMerge")//子件合并编码

                .addLeftJoin("TCG_InvoiceRegist IR ON IR.InvoiceOffsetId = A.Id AND IR.EffectStock = 1")//发票登记单
                .addField("IR.InvoiceNo AS invoiceNo")//发票号码
                .addField("IR.InvoiceDay AS invoiceDay")//开票日期
                .addField("IR.AmountNoTax AS amountNoTax")//不含税金额
                .addField("IR.Tax AS invoiceTax")//税额
                .addField("IR.AmountWithTax AS amountWithTax")//含税金额
                .addField("IR.TaxPercent AS taxPercent")//统一税点
                .addField("IR.AnnexFile AS annexFile")//发票附件

                .addLeftJoin("TCG_InvoiceRegistItem IRI ON IRI.InvoiceOffsetItemId = S.Id AND IRI.Status = 1 ")//发票登记单子表
                .addField("IRI.SubSinglePriceNoTax AS subSinglePriceNoTax")//子件单价（不含税）
                .addField("IRI.SubTotalPriceNoTax AS subTotalPriceNoTax")//子件总额（不含税）
                .addField("S.OffsetAmount - IRI.SubTotalPriceNoTax AS subTotalPrice")//子件总税额 = 子件总额（含税）- 子件总额（不含税）

                .addField("S.OffsetAmount / S.OffsetNum AS subPurchasePrice")//子件采购单价、子件单价（含税） = 子件总额（含税） / 子件数量

                .setEffectStock(1)
        //排序
        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgInvoiceOffset cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgInvoiceOffset cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgInvoiceOffset> util = new ExportExcelUtils<>(new TcgInvoiceOffset());
            String toFilePath = util.exportExcel(listData, listField, "发票管理");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 登记取消
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/cancelInfo")
    @ResponseBody
    public R cancelInfo(HttpServletRequest request, Long id){
        try {
            //登记取消
            return tcgInvoiceOffsetService.cancelInfo(id);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }








}